#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#define MAX_BUFFER_SIZE 256
#define GATEWAY_IP "192.168.31.1"
#define PING_COUNT 3

int main() {
    // 检查 eth0 网口是否连接网线
    printf("请插入 eth0 网线...\n");
    while (1) {
        FILE *file = fopen("/sys/class/net/eth0/carrier", "r");
        if (file == NULL) {
            printf("无法读取 /sys/class/net/eth0/carrier 文件\n");
            return 1;
        }

        char buffer[MAX_BUFFER_SIZE];
        fgets(buffer, MAX_BUFFER_SIZE, file);
        fclose(file);

        if (strcmp(buffer, "1\n") == 0) {
            printf("eth0 网线已插入\n");
            break;
        }
        sleep(1);
    }

    // 获取网关的 IP 地址
    struct hostent *host = gethostbyname(GATEWAY_IP);
    if (host == NULL) {
        printf("无法获取网关的 IP 地址\n");
        return 1;
    }
    struct in_addr **addr_list = (struct in_addr **)host->h_addr_list;
    char gateway_ip[INET_ADDRSTRLEN];
    strncpy(gateway_ip, inet_ntoa(*addr_list[0]), INET_ADDRSTRLEN);
    printf("网关 IP 地址为: %s\n", gateway_ip);

    sleep(3);

    // 执行 ping 测试
    char ping_cmd[MAX_BUFFER_SIZE];
    snprintf(ping_cmd, MAX_BUFFER_SIZE, "ping -c %d %s", PING_COUNT, gateway_ip);
    int result = system(ping_cmd);
    if (result == 0) {
        printf("eth0 测试成功\n");
        system("echo \"$(date)：网口0测试成功\" >> /userfs/all.txt");
    } else {
        printf("eth0 测试失败\n");
        system("echo \"$(date)：网口0测试失败\" >> /userfs/all.txt");
    }


    return 0;
}
